package com.sec.android.app.myfiles.fragment.settings;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherApps;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.SettingsActivity;
import com.sec.android.app.myfiles.dialog.ConfirmDataUsageDialog;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.update.APKDownloadManager;
import com.sec.android.app.myfiles.update.UpdateChecker;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.UiUtils;

/**
 * Created by seongsu.yoon on 2016-11-24.
 */

public class AboutPageFragment extends Fragment implements UpdateChecker.StubUpdateCheckListener {
    private Context mContext;
    private Activity mActivity;
    private static final float FULL_VIEW_WEIGHT = 1.0f;

    private boolean mIsCloudEnabled = false;

    private Button mMyFilesUpdateButton;
    private TextView mMyFilesVersionCheck;
    private ProgressBar mMyFilesVersionLoading;
    private boolean mMyFilesUpdateAvailable = false;

    private Button mCloudUpdateButton;
    private TextView mCloudVersionCheck;
    private ProgressBar mCloudVersionLoading;
    private boolean mCloudUpdateAvailable = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getContext();
        mActivity = getActivity();

        if (mActivity != null) {
            View contentsView = mActivity.findViewById(R.id.settings_layout_container);
            if (contentsView != null) {
                contentsView.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, FULL_VIEW_WEIGHT));
            }
            ((SettingsActivity) mActivity).setActionBar(R.string.about_page);
            ((SettingsActivity) mActivity).removeActionBarDivider();
        }

        View rootView;
        if (UiUtils.getScreenState(mContext) == AppConstants.PORTRAIT) {
            if (needReverseOption()) {
                rootView = inflater.inflate(R.layout.about_page_layout_land, container, false);
            } else {
                rootView = inflater.inflate(R.layout.about_page_layout, container, false);
            }
        } else {
            if (needReverseOption()) {
                rootView = inflater.inflate(R.layout.about_page_layout, container, false);
            } else {
                rootView = inflater.inflate(R.layout.about_page_layout_land, container, false);
            }
        }
        refreshLayoutMargin(rootView);
        ((SettingsActivity) getActivity()).setScreenPath(SamsungAnalyticsLog.ScreenPath.SETTINGS_ABOUT);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mIsCloudEnabled = UiUtils.isCloudGatewayEnabled(mContext);
        if (mIsCloudEnabled) {
            setCurrentVersionCheckForCloudGateway(view);
        }
        setCurrentVersionCheckForMyFiles(view);
        setAppInfo(view);
        setOpenSourceLicense(view);
        checkUpdateStatus();
        setIconColor(view);
    }

    @Override
    public void onUpdateCheckResult(boolean hasMyFilesUpdate, boolean hasCloudUpdate) {
        Log.d(this, "onUpdateCheckResult : MyFiles - " + hasMyFilesUpdate + ", Cloud - " + hasCloudUpdate);
        updateButtonView(hasMyFilesUpdate, hasCloudUpdate);
        if (!hasMyFilesUpdate && !hasCloudUpdate) {
            APKDownloadManager.getInstance(mContext.getApplicationContext()).setVersionChecking(false);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case R.string.use_network_connection:
                if (resultCode == Activity.RESULT_OK) {
                    mMyFilesUpdateButton.setVisibility(View.GONE);
                    mMyFilesUpdateButton.setOnClickListener(new UpdateMyFilesBtnClickListener(this));
                    if (mIsCloudEnabled) {
                        mCloudUpdateButton.setVisibility(View.GONE);
                        mCloudUpdateButton.setOnClickListener(new UpdateCloudBtnClickListener(this));
                    }
                    setTextForStatus(UiUtils.isNetworkOn(mContext));
                } else {
                    mMyFilesUpdateButton.setOnClickListener(new UpdateMyFilesBtnClickListener(this));
                    if (mIsCloudEnabled) {
                        mCloudUpdateButton.setOnClickListener(new UpdateCloudBtnClickListener(this));
                    }
                    setTextForStatus(false);
                }
                break;
            default:
                break;
        }
    }

    private void checkUpdateStatus() {
        Context appContext = mContext.getApplicationContext();

        showLoading(true);
        APKDownloadManager.Result result = APKDownloadManager.getInstance(appContext).needVersionUpdateAboutMyFiles(this, !mIsCloudEnabled);
        if (!UpdateChecker.getInstance(appContext).isLoading()) {
            updateButtonView(result.needMyFilesUpdate, result.needCloudUpdate);
        }
    }

    private void updateButtonView(boolean hasMyFilesUpdate, boolean hasCloudUpdate) {
        if (isAdded()) {
            mMyFilesUpdateAvailable = hasMyFilesUpdate;
            mCloudUpdateAvailable = hasCloudUpdate;
            showLoading(false);

            if (hasMyFilesUpdate) {
                mMyFilesVersionCheck.setText(getString(R.string.about_page_new_version_available));
                mMyFilesUpdateButton.setText(getString(R.string.about_page_update));
                mMyFilesUpdateButton.setVisibility(View.VISIBLE);
            } else {
                mMyFilesVersionCheck.setText(getString(R.string.about_page_lasted_version_installed));
                mMyFilesUpdateButton.setVisibility(View.GONE);
            }

            if (mIsCloudEnabled) {
                if (hasCloudUpdate) {
                    mCloudVersionCheck.setText(getString(R.string.about_page_new_cloud_version_available));
                    mCloudUpdateButton.setText(getString(R.string.about_page_update));
                    mCloudUpdateButton.setVisibility(View.VISIBLE);
                } else {
                    mCloudVersionCheck.setText(getString(R.string.about_page_lasted_version_installed));
                    mCloudUpdateButton.setVisibility(View.GONE);
                }
            }
        }
    }

    private void setCurrentVersionCheckForCloudGateway(View view) {
        try {
            TextView cloudName = (TextView) view.findViewById(R.id.about_cloud_gateway_name);
            Button cloudInfoBtn = (Button) view.findViewById(R.id.about_cloud_gateway_info);
            TextView cloudVersion = (TextView) view.findViewById(R.id.about_cloud_gateway_version);
            cloudName.setVisibility(View.VISIBLE);
            cloudInfoBtn.setVisibility(View.VISIBLE);
            cloudVersion.setVisibility(View.VISIBLE);

            PackageInfo cloudInfo = mContext.getPackageManager().getPackageInfo(AppConstants.CLOUD_GATEWAY_PACKAGE_NAME, 0);
            cloudVersion.setText(getString(R.string.about_page_version, cloudInfo.versionName));
            mCloudVersionCheck = (TextView) view.findViewById(R.id.about_cloud_gateway_version_check);
            mCloudUpdateButton = (Button) view.findViewById(R.id.about_cloud_gateway_update_btn);
            mCloudVersionLoading = (ProgressBar) view.findViewById(R.id.about_cloud_gateway_version_loading);

            if (AppFeatures.isChinaModel() && !PreferenceUtils.getDoNotShowDataUsagePopup(mContext)) {
                mCloudUpdateButton.setOnClickListener(new UpdateCloudBtnClickListener(this));
            } else {
                mCloudVersionCheck.setText(getString(R.string.about_page_lasted_version_installed));
                mCloudUpdateButton.setOnClickListener(new UpdateCloudBtnClickListener(this));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(this, "setCurrentVersionCheckForCloudGateway() - NameNotFoundException : " + e.getMessage());
        }
    }

    private void setCurrentVersionCheckForMyFiles(View view) {
        try {
            PackageInfo appInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            TextView appVersion = (TextView) view.findViewById(R.id.about_app_version);
            appVersion.setText(getString(R.string.about_page_version, appInfo.versionName));
            mMyFilesVersionCheck = (TextView) view.findViewById(R.id.about_app_version_check);
            mMyFilesUpdateButton = (Button) view.findViewById(R.id.about_app_update_btn);
            mMyFilesVersionLoading = (ProgressBar) view.findViewById(R.id.about_version_loading);

            if (AppFeatures.isChinaModel() && !PreferenceUtils.getDoNotShowDataUsagePopup(mContext)) {
                setTextForStatus(false);
                mMyFilesUpdateButton.setOnClickListener(new UpdateMyFilesBtnClickListener(this));
                ConfirmDataUsageDialog.showDataUsageDialog(this);
            } else {
                //Need to version check logic
                mMyFilesVersionCheck.setText(getString(R.string.about_page_lasted_version_installed));
                mMyFilesUpdateButton.setOnClickListener(new UpdateMyFilesBtnClickListener(this));
                setTextForStatus(UiUtils.isNetworkOn(mContext));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(this, "setCurrentVersionCheckForMyFiles() - NameNotFoundException : " + e.getMessage());
        }
    }

    private void showLoading(boolean isLoading) {
        mMyFilesVersionLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        mMyFilesVersionCheck.setVisibility(isLoading ? View.GONE : View.VISIBLE);
        if (mIsCloudEnabled) {
            mCloudVersionLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            mCloudVersionCheck.setVisibility(isLoading ? View.GONE : View.VISIBLE);
        }
    }

    private void setTextForStatus(boolean isNetwork) {
        if (isAdded()) {
            if (isNetwork) {
                if (!mMyFilesUpdateAvailable && !mCloudUpdateAvailable) {
                    PreferenceUtils.setAvailAppUpdate(mContext, false);
                }

                if (mMyFilesUpdateAvailable) {
                    mMyFilesVersionCheck.setText(getString(R.string.about_page_new_version_available));
                    mMyFilesUpdateButton.setText(getString(R.string.about_page_update));
                    mMyFilesUpdateButton.setVisibility(View.VISIBLE);
                } else {
                    mMyFilesVersionCheck.setText(getString(R.string.about_page_lasted_version_installed));
                    mMyFilesUpdateButton.setVisibility(View.GONE);
                }

                if (mIsCloudEnabled) {
                    if (mCloudUpdateAvailable) {
                        mCloudVersionCheck.setText(getString(R.string.about_page_new_cloud_version_available));
                        mCloudUpdateButton.setText(getString(R.string.about_page_update));
                        mCloudUpdateButton.setVisibility(View.VISIBLE);
                    } else {
                        mCloudVersionCheck.setText(getString(R.string.about_page_lasted_version_installed));
                        mCloudUpdateButton.setVisibility(View.GONE);
                    }
                }
            } else {
                mMyFilesVersionCheck.setText(getString(R.string.about_page_unable_to_check));
                mMyFilesUpdateButton.setText(getString(R.string.about_page_retry));
                mMyFilesUpdateButton.setVisibility(View.VISIBLE);

                if (mIsCloudEnabled) {
                    mCloudVersionCheck.setText(getString(R.string.about_page_unable_to_check));
                    mCloudUpdateButton.setText(getString(R.string.about_page_retry));
                    mCloudUpdateButton.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void setAppInfo(View view) {
        final Button appInfoView = (Button) view.findViewById(R.id.about_app_info);

        appInfoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LauncherApps launcherApps = (LauncherApps) mContext.getSystemService(Context.LAUNCHER_APPS_SERVICE);
                launcherApps.startAppDetailsActivity(new ComponentName(AppConstants.MY_FILES_PACKAGE_NAME, AppConstants.MY_FILES_ACTIVITY_NAME), Process.myUserHandle(), null, null);
            }
        });

        if (mIsCloudEnabled) {
            final Button cloudInfoView = (Button) view.findViewById(R.id.about_cloud_gateway_info);
            cloudInfoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LauncherApps launcherApps = (LauncherApps) mContext.getSystemService(Context.LAUNCHER_APPS_SERVICE);
                    launcherApps.startAppDetailsActivity(new ComponentName(AppConstants.CLOUD_GATEWAY_PACKAGE_NAME, AppConstants.MY_FILES_ACTIVITY_NAME), Process.myUserHandle(), null, null);
                }
            });
        }
    }

    private void setOpenSourceLicense(View view) {
        TextView openSourceLicenseView = (TextView) view.findViewById(R.id.about_app_open_source_license);
        openSourceLicenseView.setText(Html.fromHtml("<u>" + getString(R.string.about_page_open_source) + "</u>", Html.FROM_HTML_MODE_LEGACY));

        openSourceLicenseView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mActivity != null) {
                    Fragment openSourceLicenseFragment = new OpenSourceLicenseFragment();
                    FragmentManager fm = mActivity.getFragmentManager();
                    FragmentTransaction ft = fm.beginTransaction();
                    ft.replace(R.id.settings_layout_container, openSourceLicenseFragment);
                    ft.addToBackStack(null);
                    ft.commitAllowingStateLoss();
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS_ABOUT, SamsungAnalyticsLog.Event.OPEN_SOURCE_LICENSES, null);
                }
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        UiUtils.replaceFragment(this);
        refreshLayoutMargin(getView());
    }

    private void refreshLayoutMargin(View view) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) view.findViewById(R.id.about_myfiles_layout_empty_view_top).getLayoutParams();

        float screenHeight = getScreenHeight();
        if (UiUtils.getScreenState(mContext) == AppConstants.PORTRAIT) {
            if (needReverseOption()) {
                lp.height = (int) (screenHeight * 0.081);
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            } else {
                lp.height = (int) (screenHeight * 0.085);
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            view.findViewById(R.id.about_app_link_layout_empty_view_bottom).getLayoutParams().height = (int) (screenHeight * 0.05);
        } else {
            if (needReverseOption()) {
                lp.height = (int) (screenHeight * 0.085);
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            } else {
                lp.height = (int) (screenHeight * 0.081);
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
        }
        view.findViewById(R.id.about_myfiles_layout_empty_view_bottom).setLayoutParams(lp);
    }

    private boolean needReverseOption() {
        return false;
    }

    private float getScreenHeight() {
        Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        return size.y;
    }

    private class UpdateMyFilesBtnClickListener implements View.OnClickListener {
        private AboutPageFragment mAboutFragment;

        private UpdateMyFilesBtnClickListener(AboutPageFragment fragment) {
            mAboutFragment = fragment;
        }

        @Override
        public void onClick(View view) {
            if (AppFeatures.isChinaModel() && !PreferenceUtils.getDoNotShowDataUsagePopup(mContext)) {
                ConfirmDataUsageDialog.showDataUsageDialog(mAboutFragment);
            } else {
                boolean isNetwork = UiUtils.isNetworkOn(mContext);
                setTextForStatus(isNetwork);
                sendSALog();
                if (isNetwork) {
                    if (mMyFilesUpdateButton.getText().equals(getString(R.string.about_page_update))) {
                        UpdateChecker.getInstance(mContext).callGalaxyAppsDeepLink(mContext, mContext.getPackageName());
                    } else {
                        mMyFilesUpdateButton.setVisibility(View.GONE);
                    }
                } else {
                    Toast.makeText(mContext, mContext.getText(R.string.no_network_connection), Toast.LENGTH_LONG).show();
                }
            }
        }

        private void sendSALog() {
            SamsungAnalyticsLog.Event event;
            if (mMyFilesVersionCheck.getText().equals(getString(R.string.about_page_update))) {
                event = SamsungAnalyticsLog.Event.UPDATE;
            } else {
                event = SamsungAnalyticsLog.Event.RETRY;
            }
            SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS_ABOUT, event, null);
        }
    }

    private class UpdateCloudBtnClickListener implements View.OnClickListener {
        private AboutPageFragment mAboutFragment;

        private UpdateCloudBtnClickListener(AboutPageFragment fragment) {
            mAboutFragment = fragment;
        }

        @Override
        public void onClick(View view) {
            if (AppFeatures.isChinaModel() && !PreferenceUtils.getDoNotShowDataUsagePopup(mContext)) {
                ConfirmDataUsageDialog.showDataUsageDialog(mAboutFragment);
            } else {
                boolean isNetwork = UiUtils.isNetworkOn(mContext);
                setTextForStatus(isNetwork);
                sendSALog();
                if (isNetwork) {
                    if (mCloudUpdateButton.getText().equals(getString(R.string.about_page_update))) {
                        UpdateChecker.getInstance(mContext).callGalaxyAppsDeepLink(mContext, AppConstants.CLOUD_GATEWAY_PACKAGE_NAME);
                    } else {
                        mCloudUpdateButton.setVisibility(View.GONE);
                    }
                } else {
                    Toast.makeText(mContext, mContext.getText(R.string.no_network_connection), Toast.LENGTH_LONG).show();
                }
            }
        }

        private void sendSALog() {
            SamsungAnalyticsLog.Event event;
            if (mCloudVersionCheck.getText().equals(getString(R.string.about_page_update))) {
                event = SamsungAnalyticsLog.Event.UPDATE;
            } else {
                event = SamsungAnalyticsLog.Event.RETRY;
            }
            SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS_ABOUT, event, null);
        }
    }

    private void setIconColor(View view) {
        String packageName = Settings.System.getString(mContext.getContentResolver(), "current_sec_active_themepackage");
        if (packageName != null) {
            ImageView iconView = (ImageView) view.findViewById(R.id.about_app_icon);
            if (iconView != null) {
                iconView.setColorFilter(mContext.getColor(R.color.color_primary_dark));
            }
        }
    }
}
